package register

class Image implements Comparable {
    Pet pet
    Integer size
    byte[] data
    String contentType
    Integer width
    Integer height
    Date dateCreated = new Date()
    Date lastUpdated = new Date()

    static belongsTo = [ Pet ]

    static mapping = {
        pet index: 'images_index', unique: true
        size index: 'images_index', unique: true
        data type: 'binary'
    }
  
    static constraints = {
        data(maxSize: MAX_SIZE)
    }
    
    static final Integer MAX_SIZE = 10 * 1024 * 1024
    
    static final Integer Original = 1
    static final Integer Large = 2
    static final Integer Medium = 3
    static final Integer Small = 4
  
    static final Integer[] Widths =  [ 0, 0, 500, 250, 100 ]
    static final Integer[] Heights = [ 0, 0, 500, 250, 100 ]
  
    static final String[] Names = [ '', 'Original', 'Large', 'Medium', 'Small' ]
  
    int compareTo(obj) {
        size.compareTo(obj.size)
    }

    String filename() {
        Image.filename(pet.id, size)
    }
  
    static String filename(long id, int size) {
        if (size == Original) {
            return "${id}-${Names[size]}.jpg"
        }
        else {
            return "${id}-${Names[size]}.png"
        }
    }
}